/*
 * Copyright (c) 2015. 石头哥哥
 */

package com.comom.manager.kit;

import com.mysql.jdbc.AbandonedConnectionCleanupThread;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

/**
 * Created by 石头哥哥 on 15-9-16.
 * dcServer-parent
 * com.mengchong.server.service
 * connecting qq: 502959937
 * my blog: http://my.oschina.net/chenleijava
 * comtents:  取消 web注册 mysql驱动, 关闭定时器
 */
@WebListener
public class ContainerContextClosedHandler implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // nothing to do
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {

        Enumeration<Driver> drivers = DriverManager.getDrivers();
        // clear drivers
        while (drivers.hasMoreElements()) {
            try {
                Driver     driver = drivers.nextElement();
                DriverManager.deregisterDriver(driver);

            } catch (SQLException ex) {
                // deregistration failed, might want to do something, log at the very least
            }
        }

        // MySQL driver leaves around a thread. This static method cleans it up.
        try {
            AbandonedConnectionCleanupThread.shutdown();
        } catch (InterruptedException e) {
            // again failure, not much you can do
        }

        //close quartz scheduler
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.shutdown();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }
}
